package com.lktx.auto.chat;

import cn.hserver.plugin.web.handlers.Ws;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dtflys.forest.Forest;
import com.lktx.auto.bean.ChatMessage;

public class ChatHandler {

    public static void handler(Ws ws, ChatMessage chatMessage){
        StringBuffer deepSeekStr = new StringBuffer();
        Forest.post("http://127.0.0.1:11434/api/chat")
                .addBody(chatMessage)
                .contentType("application/json")
                .sse()
                .addConsumer("{\"model\"", (eventSource, name, value) -> {
                    JSONObject entries = JSONUtil.parseObj(name + ":" + value);
                    String str = entries.getJSONObject("message").getStr("content");
//                    System.out.print(str);
                    if (ws!=null){
                        deepSeekStr.append(str);
                        ws.send(str);
                    }
                })
                .setOnClose(event -> {
                    chatMessage.addAssistantMessage(deepSeekStr.toString());
                    if (ws!=null){
                        //发送图片
//                        ws.send("![DRAWING](https://foruda.gitee.com/avatar/1676994350313868720/1893827_heixiaomas_admin_1578961913.png)");
                        ws.getCtx().close();
                    }
                })
                .listen();
    }

    public static void main(String[] args) {

        ChatHandler.handler(null,ChatMessage.newUserMessage("你是什么模型？"));

    }
}
